package com.sun.dream.fish.util;

import com.google.common.base.Throwables;

import java.io.IOException;
import java.io.UncheckedIOException;
import java.lang.reflect.InvocationTargetException;

/**
 * Description:  将被检测异常转化成未检测异常
 * Created By ljl on 2023/12/05.
 */
public class UnChecked {
    private UnChecked() {
    }

    public static void wrap(DSFCheckedRunnable checkedRunnable) {
        try {
            checkedRunnable.run();
        } catch (Throwable throwable) {
            throw propagate(throwable);
        }
    }

    public static <T> T wrap(DSFCheckedSupplier<T> supplier) {
        try {
            return supplier.get();
        } catch (Throwable throwable) {
            throw propagate(throwable);
        }
    }

    private static RuntimeException propagate(Throwable throwable) {
        if (throwable instanceof InvocationTargetException) {
            throw propagate(throwable.getCause());
        } else if (throwable instanceof IOException) {
            throw new UncheckedIOException((IOException) throwable);
        } else {
            Throwables.throwIfUnchecked(throwable);
            throw new RuntimeException(throwable);
        }
    }
}
